package com.siping.leetcode.剑指offer.day01;

/**
 * @author Yang Xu
 * @date 2021/8/17 17:41
 * @description: 第二种解题思路维护双链表
 */
public class MinStack2 {
    private Node valHead;
    private Node minHead;

    public MinStack2() {

    }

    public void push(int val) {
        if (valHead == null) {
            valHead = new Node(val);
            minHead = new Node(val);
        } else {
            valHead = new Node(val, valHead);
            minHead = new Node(Math.min(val, minHead.val), minHead);
        }
    }

    public void pop() {
        minHead = minHead.nex;
        valHead = valHead.nex;
    }

    public int top() {
        return valHead.val;
    }

    public int getMin() {
        return minHead.val;
    }

    private class Node {
        private int val;
        private Node nex;

        public Node(int val) {
            this.val = val;
        }

        public Node(int val, Node nex) {
            this.val = val;
            this.nex = nex;
        }
    }

    public static void main(String[] args) {
        MinStack2 minStack = new MinStack2();
        minStack.push(-10);
        minStack.push(14);
        System.out.println(minStack.getMin());
        System.out.println(minStack.getMin());
        minStack.push(-20);
        System.out.println(minStack.getMin());
        System.out.println(minStack.getMin());
        System.out.println(minStack.top());
        System.out.println(minStack.getMin());
        minStack.pop();

        minStack.push(10);
        minStack.push(-7);
        System.out.println(minStack.getMin());
        minStack.push(-7);
        minStack.pop();

        System.out.println(minStack.top());
        System.out.println(minStack.getMin());
        minStack.pop();

    }
}
